package net.lab1024.smartadmin.module.support.quartz.task.run;

import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.WxCpDepart;
import net.lab1024.smartadmin.common.domain.ITask;
import net.lab1024.smartadmin.common.weixin.WxCpConfiguration;
import net.lab1024.smartadmin.module.system.department.DepartmentDao;
import net.lab1024.smartadmin.module.system.department.domain.entity.DepartmentEntity;
import net.lab1024.smartadmin.module.system.systemconfig.SystemConfigService;
import net.lab1024.smartadmin.module.system.systemconfig.constant.SystemConfigEnum;
import net.lab1024.smartadmin.util.SmartDateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * [ 同步部门 ]
 *
 * @author 五千
 * @version 1.0
 * @company 1024lab.net
 * @copyright (c) 2018 1024lab.netInc. All rights reserved.
 * @date 2021/3/24 0013 下午 14:26
 * @since JDK1.8
 */
@Slf4j
@Component("cpDepartmentTask")
public class cpDepartment implements ITask {
    @Autowired
    private SystemConfigService systemConfigService;

    @Autowired
    private DepartmentDao departmentDao;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void execute(String paramJson) throws Exception {

        Integer agentId = Integer.valueOf(systemConfigService.getCacheByKey(SystemConfigEnum.Key.CP_AGENTID).getConfigValue());
        WxCpService wxCpService = WxCpConfiguration.getCpService(agentId);
        List<WxCpDepart> list = wxCpService.getDepartmentService().list(0L);
        List<Long> rootDepartment = new ArrayList<>();//创建一个临时部门根id缓存
        for(WxCpDepart item:list){
            DepartmentEntity departmentEntity = departmentDao.selectById(item.getId());

            boolean isInsert = false;
            if(departmentEntity == null ){
                departmentEntity = new DepartmentEntity();
                isInsert = true;
            }
            departmentEntity.setId(item.getId());
            departmentEntity.setName(item.getName());

            if(true|| rootDepartment.contains(item.getId())){
                departmentEntity.setParentId(item.getParentId());
            }else{
                departmentEntity.setParentId(1L);
            }
            rootDepartment.add(item.getId());

            departmentEntity.setSort(item.getOrder());
            departmentEntity.setUpdateTime(new Date());
            if(isInsert){
                //待主键插入数据；
                departmentEntity.setCreateTime(new Date());
                departmentDao.insertId(departmentEntity);
            }else{
                departmentDao.updateById(departmentEntity);
            }
        }
        log.warn("{}-今天搬了{}块砖,paramJson:{}", SmartDateUtil.formatYMDHMS(new Date()), System.currentTimeMillis(), paramJson);
    }
}
